<template>
    <div class="clearfix">
        <a-upload :disabled="flag"  action="" list-type="picture-card" :file-list="fileList" @preview="handlePreview" @change="handleChange"
            :customRequest="customRequest" :before-upload="value => beforeUpload(value, 1)"
            :remove="file => deleteFileItem(file, 1)">
            <div v-if="fileList.length == 0">
                <a-icon type="plus" />
                <div class="ant-upload-text">
                    上传签名
                </div>
            </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%;" :src="previewImage" />
        </a-modal>
    </div>
</template>

<script>
import { downloadEnclosureHis } from "@/api/Common"; //下载图片
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
export default {
    props: ['item', 'text','flag'],
    data() {
        return {
            previewImage: '',//图片链接
            loading: false,
            fileList: [],
            previewVisible: false,

        }
    },
    methods: {
        /* 关闭预览放大图片 */
        handleCancel() {
            this.previewVisible = false;
        },
        /* 上传图片前检验 */
        beforeUpload(file, index) {
            this.currentImg = index
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('只能上传图片!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('图片必须小于2MB!');
            }
            return isJpgOrPng && isLt2M;
        },
        /* 赋值预览图片 */
        async handlePreview(file) {
            console.log(file)
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            this.previewImage = file.url || file.preview;
            this.previewVisible = true;
        },
        /* 上传图片 */
        handleChange({ fileList }) {
            fileList[0].status = 'success'
            this.fileList = fileList;
        },
        /* 覆盖上传 */
        customRequest(data) {
            console.log(data)
        },
        /* 删除上传图片 */
        deleteFileItem(file, indexs) {
           this.$message.error('签名不能删除!');
        },
        /* base64转Blob */
        dataURLtoBlob(dataurl) {
            var arr = dataurl.split(","),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        },
        /* Blob转File */
        blobToFile(theBlob, fileName) {
            theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
            theBlob.name = fileName; // 文件名
            return new File([theBlob], fileName, {
                type: theBlob.type,
                lastModified: Date.now(),
            });
        },

    },
    watch: {
        /* 监听是否有已经上传的文件,通过接口展示 */
        text: {
            async handler(newVal, oldVal) {
                let res = await downloadEnclosureHis({
                    relationTableId: this.item.JobRecordDetailID,
                });
                if (res.Data != null) {
                    let { FilebyteStr, Name, } = res.Data;
                    if (FilebyteStr != null) {
                        let base64 = `data:image/png;base64,${FilebyteStr}`;
                        let blob = this.dataURLtoBlob(base64);
                        let file = this.blobToFile(blob, Name);
                        this.fileList = [];
                        let obj = {
                            url: base64,
                            originFileObj: file,
                            status: "done",
                            uid: '-1',
                            name: file.name
                        };
                        this.fileList.push(obj);
                    }
                }
            },
            immediate: true,
            deep: true,
        },
        /* 监听图片列表是否有变化 */
        fileList: {
            handler(newVal, oldVal) {
                console.log(newVal)
                if (newVal.length > 0) {
                    this.item.imgList = newVal
                }
            },
            immediate: true,
            deep: true,
        },
    },
}
</script>

<style></style>